package com.atguigu.gmall.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.IpUtil;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;


/**
 * 用户的controller
 */
@RestController
@RequestMapping(value = "/user")
public class UserInfoController {
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private HttpServletRequest request;

    @PostMapping(value = "/login")
    public Result<Map> login(String username,
                             String password){
        //登陆
        UserInfo userInfo = userInfoService.login(username, password);
        //登陆成功,生成令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        //自定义存储对象
        Map<String,Object> map = new HashMap<>();
        map.put("userId",userInfo.getId());
        //Ip地址
        map.put("ip", IpUtil.getIpAddress(request));
        //保存到Redis中
        stringRedisTemplate.boundValueOps(token).set(JSONObject.toJSONString(map));
        //返回用户
        Map<String,String> result = new HashMap<>();
        result.put("token",token);
        result.put("nickName",userInfo.getNickName());
        return Result.ok(result);
    }

    @GetMapping(value = "/getUserAddress")
    public Result<List<UserAddress>>  getUserAddress(){
        Long userId = 1L;
        List<UserAddress> userAddressList = userInfoService.getUserAddressList(userId);
        return Result.ok(userAddressList);
    }
}
